package org.Lin.client;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.util.List;

public class chatGUI extends Application {

    private TextArea questionArea;
    private ListView<String> historyList;

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox(10);

        Label questionLabel = new Label("请输入你的问题");
        questionArea = new TextArea();
        questionArea.setPromptText("输入你的问题...");

        HBox buttons = new HBox(10);
        Button sendButton = new Button("发送");
        Button refreshButton = new Button("刷新");

        CheckBox continuousChatBox = new CheckBox("连续对话");

        buttons.getChildren().addAll(sendButton, refreshButton, continuousChatBox);

        Label historyLabel = new Label("历史记录");
        historyList = new ListView<>();

        root.getChildren().addAll(questionLabel, questionArea, buttons, historyLabel, historyList);

        Scene scene = new Scene(root, 600, 500);
        primaryStage.setScene(scene);
        primaryStage.setTitle("AI问答");
        primaryStage.show();

        setupEventHandlers(sendButton, refreshButton, continuousChatBox);
    }

    private void setupEventHandlers(Button sendButton, Button refreshButton, CheckBox continuousChatBox) {
        sendButton.setOnAction(e -> {
            String question = questionArea.getText().trim();
            if (!question.isEmpty()) {
                String userId = continuousChatBox.isSelected() ? "chat" : "anonymous";
                dbUtil.addQuestion(question, userId);
                questionArea.clear();
                Alert alert = new Alert(Alert.AlertType.INFORMATION, "问题已提交，请刷新查看回答。");
                alert.showAndWait();
            }
        });

        refreshButton.setOnAction(e -> {
            List<questionModel> answered = dbUtil.getAnsweredQuestions();
            historyList.getItems().clear();
            for (questionModel q : answered) {
                historyList.getItems().add("[" + q.getTimestamp() + "] Q: " + q.getQuestion());
                historyList.getItems().add("[" + q.getTimestamp() + "] " + q.getModelUsed() + ": " + q.getAnswer());
            }
        });
    }

}